<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/8/19 19:26
 * Modified Time: 2019/8/19 19:26
 * Version: 2.0
 */

namespace App\Modules\System\Services;


use App\Exceptions\AllValidatorException;
use App\Lib\File\AliOSS;
use App\Lib\Utilities;
use App\Modules\Activity\Services\ActivityService;
use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\Employee\Repositories\PortfolioRepository;
use App\Modules\Store\Repositories\StoreRepository;
use App\Modules\System\Repositories\StoreResourceRepository;
use EasyWeChat\Factory;
use Flower\Core\Repository\Eloquent\BaseService;
use Intervention\Image\AbstractFont;
use Intervention\Image\Facades\Image;

class ShareService extends BaseService
{
	protected $portfolioRepository;
	protected $storeResourceRepository;
	protected $storeRepository;
	protected $activityService;
	protected $employeeRepository;
	protected $aliOSS;

	public function __construct(PortfolioRepository $portfolioRepository,
	                            StoreResourceRepository $storeResourceRepository,
	                            StoreRepository $storeRepository,
	                            ActivityService $activityService,
	                            EmployeeRepository $employeeRepository,
	                            AliOSS $aliOSS)
	{
		$this->portfolioRepository = $portfolioRepository;
		$this->storeResourceRepository = $storeResourceRepository;
		$this->storeRepository = $storeRepository;
		$this->activityService = $activityService;
		$this->employeeRepository = $employeeRepository;
		$this->aliOSS = $aliOSS;
	}

	//分享作品
	public function sharePortfolio($portfolio_id)
	{
		//获取作品截图
		$portfolio = $this->portfolioRepository->getPortfolioById($portfolio_id);

		if (!$portfolio) {
			throw new AllValidatorException(['msg' => '作品不存在']);
		}
		$img_url = $portfolio->image;
		if (!$img_url) {
			throw new AllValidatorException(['msg' => '作品图不存在']);
		}
		$barber_id = $portfolio->user_id;
		$barber = $this->employeeRepository->getUserInfo($barber_id);

		$title = $barber->nick;
		$logo = $barber->picture->image;
		$text = $portfolio->desc?$portfolio->desc:'我发布了一个新作品，一起来看一看吧。';
		$path = '/pages/video-video/video-video?source=35&&index=0&&num=5&&portfolio_id=' . $portfolio_id;
		$qrcode = $this->createWeChatAppCode($path);

		return $this->returnData($img_url, $logo, $title, $text, $qrcode,1);
	}

	//分享理发师
	public function shareBarber($barber_id, $store_id)
	{
		$barber = $this->employeeRepository->getUserBaseInfo($barber_id);
		if (!$barber) {
			throw new AllValidatorException(['msg' => '理发师不存在']);
		}
		//获取理发师半身照
		$img = $this->employeeRepository->getEmployeeProfile($barber_id)->profile_picture;

		if (!$img) {
			throw new AllValidatorException(['msg' => '没有找到半身照']);
		}

		$title = $barber->nick;
		$logo = $barber->picture->image;
		$text = $barber->introduction;

		if (!$text) {
			$text = '我已经入驻花县令啦，期待为你服务哦。';
		}

		$path = '/pages/barber-details/barber-details?source=13&&barber_id=' . $barber_id . '&&store_id=' . $store_id;
		$qrcode = $this->createWeChatAppCode($path);

		return $this->returnData($img, $logo, $title, $text, $qrcode);
	}

	//分享店铺
	public function shareStore($store_id)
	{
		//获取店铺图片
		$img = $this->storeResourceRepository->getStorePicture($store_id)->first()->toArray();

		$img = isset($img['image']) ? $img['image'] : null;
		if (!$img) {
			throw new AllValidatorException(['msg' => '没有找到店铺图']);
		}

		$store = $this->storeRepository->getStoreNameById($store_id);

		if (!$store) {
			throw new AllValidatorException(['msg' => '没有找到店铺']);
		}
		$title = $store->store_name;
		$logo = $store->picture->image;
		$text = $store->profile;

		if (!$text) {
			$text = '本店已在花县令上线啦,欢迎扫码预约。';
		}
		$path = '/pages/shop/shop?source=5&&store_id=' . $store_id;
		$qrcode = $this->createWeChatAppCode($path);

		return $this->returnData($img, $logo, $title, $text, $qrcode);
	}

	//分享活动
	public function shareActivity($activity_id)
	{
		$activity = $this->activityService->getActivity($activity_id);
		if (!$activity) {
			throw new AllValidatorException(['msg' => '活动不存在']);
		}
		$img = $activity->playbill;

		if (!$img) {
			throw new AllValidatorException(['msg' => '暂无活动图']);
		}
		$store_id = $activity->store_id;
		$store = $this->storeRepository->getStoreNameById($store_id);
		$title = $activity->title;
		$logo = $store->picture->image;
		$text = $activity->content;

		$path = '/pages/active_details/active_details?source=22&&activity_id=' . $activity_id;
		$qrcode = $this->createWeChatAppCode($path);

		return $this->returnData($img, $logo, $title, $text, $qrcode);
	}



	public function WxAppPath()
	{
		$path = '/pages/codeCard/codeCard?cardId=1&barber_id=1';
		return  $this->createWeChatAppCode($path);
	}















	protected function returnData($img_url, $logo, $title, $text, $qrcode, $video = 0)
	{
		$img_name = explode('/', $img_url);
		$img_name = end($img_name);
		if($video){
            $img_name = md5(time().$img_url).'.jpg';
        }
		$this->saveImage($img_url, public_path() . '/tmp/' . $img_name);
		$img_url = ENV('HOST_NAME') . '/tmp/' . $img_name;

		$logo_name = explode('/', $logo);
		$logo_name = end($logo_name);
		$this->saveImage($logo, public_path() . '/tmp/' . $logo_name);
		$logo = ENV('HOST_NAME') . '/tmp/' . $logo_name;


		return [
			'image' => $img_url,
			'title' => $title,
			'logo' => $logo,
			'text' => $text,
			'qrcode' => $qrcode
		];
	}

	public function createWeChatAppCode($path)
	{

		$config = [
			'app_id' => config('constant.easyWechatApp.app_id'),
			'secret' => config('constant.easyWechatApp.secret'),

			// 下面为可选项
			// 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
			'response_type' => 'array',

			'log' => [
				'level' => 'debug',
				'file' => storage_path() . '/logs/wechat.log',
			],
		];


		$app = Factory::miniProgram($config);

		$res = $app->app_code->get($path, [
			'width' => 600,
			'line_color' => [
				'r' => 105,
				'g' => 166,
				'b' => 134,
			],
		]);

		if ($res instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
			$filename = $res->save(public_path() . '/tmp/images/qrcode/', md5(time() . rand(1000, 9999)) . '.png');
		}

		$qrcode = '/tmp/images/qrcode/' . $filename;
//        $filename = md5($qrcode);
//        $qrcode = $this->aliOSS->uploadByPath($qrcode, 'tmp/' . date('Y-m-d', time()), $filename, 'png');
		return ENV('HOST_NAME') . $qrcode;
	}


	/**
	 * 保存url图片
	 * @param $path
	 * @param $image_name
	 */
	protected function saveImage($path, $image_name)
	{
		$ch = curl_init($path);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
		$img = curl_exec($ch);
		curl_close($ch);
//$image_name就是要保存到什么路径,默认只写文件名的话保存到根目录
		$fp = fopen($image_name, 'w');//保存的文件名称用的是链接里面的名称
		fwrite($fp, $img);
		fclose($fp);
		return true;
	}

}